<?php
/**
 * Created by JiangJiaCai.
 * User: Administrator
 * Date: 2017/7/11 0011
 * Time: 23:35
 */

namespace ext\service;


use App\Models\QdcsClass;
use com_jjcbs\lib\Service;
use ext\dao\ClassDaoImpl;

class ClassServiceImpl extends Service
{
    public $classDaoImpl;

    public function __construct()
    {
        $this->classDaoImpl = new ClassDaoImpl();
    }

    public function exec()
    {
        // TODO: Implement exec() method.
    }

    /**
     * 获取满足select 使用的 id => 名称
     */
    public function getSelectOption(){
        $arr = $this->classDaoImpl->getAllList(QdcsClass::class);
        $temp = [];
        $temp[0] = '顶级分类';
        foreach ($arr as $v){
            $temp[$v->id] = $v->name;
        }
        return $temp;
    }

    /**
     * get class path by cls_id
     * @param int $cls_id
     * @param string $sign
     * @return string path
     */
    public function getClassPath(int $cls_id , string $sign = '/'){
        return implode($sign , array_reverse($this->getPathArr($this->classDaoImpl->getOne(QdcsClass::class , $cls_id))));
    }

    /**
     * get childs list
     * @param int $pid
     * @param array $temp
     * @return array
     */
    public function getChildOption(int $pid , array  $temp = []){
        //get child
        $arr = $this->classDaoImpl->getList(QdcsClass::class , 100 , [
            'parent_id' => $pid
        ]);
        $temp = [];
        foreach ($arr as $v){
            $temp[$v->id] = $v->name;
        }
        return $temp;
    }

    /**
     * get parent class stopped return zero
     * @param QdcsClass $qdcsClass
     * @param $path
     * @return array;
     */
    private function getPathArr(QdcsClass $qdcsClass , &$path = []){
        array_push($path , $qdcsClass->name);
        if (  0 == $qdcsClass->parent_id){
            return $path;
        }else{
            return $this->getPathArr($this->classDaoImpl->getOne(QdcsClass::class , $qdcsClass->parent_id) , $path);
        }
    }


}